﻿Imports Aricie.DNN.Diagnostics
Imports DotNetNuke.Services.Log.EventLog
Imports Aricie.Services

Namespace LuceneSearch.Monitoring.Logging
    Public Class DirectToAsyncLogger
        Inherits PerformanceLogger

        Public Overloads Shared Function Instance() As DirectToAsyncLogger
            Return ReflectionHelper.GetSingleton(Of DirectToAsyncLogger)()
        End Function

        Public Overrides Sub AddDebugInfo(objToLog As Aricie.DNN.Diagnostics.StepInfo, serialize As Boolean)
            'HACK: in order to sidestep the fact that the debug logger uses its own thread (which defeats the sequence used by the async worker and the order of logs)
            ' we override this method in order to go straight to the AsyncWorker

            Dim objEventLogInfo As New LogInfo()
            Try
                Dim startTimeStamp As DateTime = Me.GetTimeStamp

                objEventLogInfo.LogTypeKey = glbDnnLogTypeKey

                If objToLog.PortalId <> -1 Then
                    objEventLogInfo.LogPortalID = objToLog.PortalId
                End If

                If AddLogTypeAndName Then
                    objEventLogInfo.AddProperty(glbDebugTypePropertyName, objToLog.DebugType)
                    objEventLogInfo.AddProperty("Name", objToLog.Name)
                End If


                Dim discardLog As Boolean
                Dim previousLogs As IList(Of LogInfo) = New List(Of LogInfo)
                Me.FillLogObject(objToLog, objEventLogInfo, discardLog, previousLogs)

                For Each objLog As LogInfo In previousLogs
                    AsyncLogger.Instance.AddLog(objLog)
                Next

                If Not discardLog Then
                    objEventLogInfo.AddProperty("Debug Processing TimeStamp", startTimeStamp.ToString("yyyy, dddd, MMMM dd, h:mm:ss.FFFFFFF"))
                    objEventLogInfo.AddProperty("Debug Processing Duration", Aricie.FormatTimeSpan(Me.GetTimeStamp.Subtract(startTimeStamp)))
                    AsyncLogger.Instance.AddLog(objEventLogInfo)
                End If
            Catch ex As Exception
                objEventLogInfo.LogProperties.Add(New LogDetailInfo("Logger Exception", ex.ToString))
                Try
                    AsyncLogger.Instance.AddLog(objEventLogInfo)
                Catch ex2 As Exception
                    ' we do nothing
                    Aricie.Services.ExceptionHelper.LogException(ex)
                End Try
            End Try

        End Sub

    End Class
End Namespace